﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LinkedList
{
    public class ListNode
    {
        public int val;
        public ListNode next;

        public ListNode() { }
        public ListNode(int x)
        {
            val = x;
        }


        // 链表节点的构造函数
        // 使用arr为参数，创建一个链表，当前的ListNode为链表头结点
        // 数组转链表
        public ListNode(int[] arr)
        {

            if (arr == null || arr.Length == 0)
                throw new Exception("arr can not be empty");

            this.val = arr[0];
            ListNode cur = this;
            for (int i = 1; i < arr.Length; i++)
            {
                cur.next = new ListNode(arr[i]);
                cur = cur.next;
            }
        }



        // 以当前节点为头结点的链表信息字符串

        public override string ToString()
        {
            StringBuilder s = new StringBuilder();
            ListNode cur = this;
            while (cur != null)
            {
                s.Append(cur.val + "->");
                cur = cur.next;
            }
            s.Append("NULL");
            return s.ToString();
        }






        // leetcode测试 不加虚拟头结点,删除链表中所有 val 值
        public ListNode removeElements(ListNode head, int val)
        {

            while (head != null && head.val == val)
            {
                ListNode delNode = head;
                head = head.next;
                delNode.next = null;
            }

            if (head == null)
                return head;

            ListNode prev = head;
            while (prev.next != null)
            {
                if (prev.next.val == val)
                {
                    ListNode delNode = prev.next;
                    prev.next = delNode.next;
                    delNode.next = null;
                }
                else
                    prev = prev.next;
            }

            return head;
        }




        // leetcode测试 加虚拟头结点,删除链表中所有 val 值
        public ListNode removeElements2(ListNode head, int val)
        {
            ListNode dummyHead = new ListNode(-1);
            dummyHead.next = head;
            ListNode prev = dummyHead;
            while (prev.next != null)
            {
                if (prev.next.val == val)
                {
                    ListNode delNode = prev.next;
                    prev.next = delNode.next;
                    delNode.next = null;
                }
                else
                    prev = prev.next;
            }

            return dummyHead.next;
        }



    }
}
